<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="pd.showSearch">
        <el-card shadow="hover">
          <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <el-form-item label="树节点名" prop="name">
              <el-input v-model="pd.queryParams.name" placeholder="请输入树节点名" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['demo:tree:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        v-loading="pd.loading" :data="pd.treeList" row-key="dataId" :default-expand-all="pd.isExpandAll" ref="treeTableRef">
        <el-table-column prop="name" label="树名称" sortable />
        <el-table-column prop="value" label="字典值" sortable width="350px" />
        <el-table-column prop="createTime" label="创建时间" sortable width="300px"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350px" >
          <template #default="scope">
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:dict:add']" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:dict:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:dict:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改测试树对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="treeFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-form-item label="父级树名" v-if="pd.dialog.title == '新增测试树' || pd.form.parentName && pd.dialog.title != '修改测试树'">
          <el-input v-model="pd.form.parentName" disabled />
        </el-form-item>
        <el-form-item label="父级值" v-if="pd.dialog.title == '新增测试树' || pd.form.parentValue && pd.dialog.title != '修改测试树'">
          <el-input v-model="pd.form.parentValue" disabled />
        </el-form-item>
        <el-form-item label="树名称">
          <el-input v-model="pd.form.name" placeholder="请输入label" />
        </el-form-item>
        <el-form-item label="字典值" v-if="pd.form.children?pd.form.children!.length <= 0:true">
          <el-input v-model="pd.form.value" placeholder="请输入字典值后两位" maxlength="2" oninput="value=value.replace(/[^a-zA-Z\d]/g, '')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tree" lang="ts">
import {DictVO, addData, delData, getDataByType, updateData} from "@/views/system/dict/api";
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const route = useRoute();

const queryFormRef = ref<ElFormInstance>();
const treeFormRef = ref<ElFormInstance>();
const treeTableRef = ref<ElTableInstance>()

const pd = reactive({
  treeList: <DictVO[]>([]),
  buttonLoading: false,
  showSearch: true,
  isExpandAll: true,
  loading: false,
  form: <DictVO>{},
  queryParams: <DictVO>{},
  rowValue: '',
  rules: <ElFormRules>{
    name: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
    value: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
    sort: [{ required: true, message: "数据顺序不能为空", trigger: "blur" }]
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

/** 查询测试树列表 */
async function getList() {
  pd.loading = true;
  const res = await getDataByType(pd.queryParams.type!);
  const data = proxy?.handleTree2<DictVO>(res.data);
  if (data) {
    pd.treeList = data;
    pd.loading = false;
  }
}

// 取消按钮
function cancel() {
  reset();
  pd.dialog.visible = false;
}

// 表单重置
function reset() {
  pd.form = <DictVO>{};
  treeFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row?: DictVO) {
  reset();
  if (row && row.dataId) {
    pd.form.parentValue = row.value;
    pd.form.parentName = row.name;
    pd.rowValue = pd.form.value;
  } else {
    pd.form.parentValue = '';
  }
  console.log(pd.form.name)
  pd.dialog.visible = true;
  pd.dialog.title = "添加测试树";
}

/** 展开/折叠操作 */
function handleToggleExpandAll() {
  pd.isExpandAll = !pd.isExpandAll;
  toggleExpandAll(pd.treeList, pd.isExpandAll)
}

/** 展开/折叠操作 */
function toggleExpandAll(data: DictVO[], status: boolean) {
  data.forEach((item) => {
    treeTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
async function handleUpdate(row: DictVO) {
  reset();
  Object.assign(pd.form, row);
  pd.form.parentValue = row.value.substring(0,row.value.length-2);
  pd.form.value = row.value.substring(row.value.length-2);
  pd.rowValue = pd.form.value;
  pd.form.name = row.name;
  pd.form.children = row.children;

  pd.dialog.visible = true;
  pd.dialog.title = "修改测试树";
}

/** 提交按钮 */
async function submitForm() {
  if (pd.form.value.length < 2){
    proxy?.$modal.msgWarning("字典值有误，请重新输入");
    return;
  }
  pd.dialog.visible = false;
  treeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      pd.form.type = pd.queryParams.type;
      if (pd.form.parentValue) pd.form.value = pd.form.parentValue + pd.form.value;
      if (pd.form.dataId) {
        await updateData(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addData(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row: DictVO) {
  if (row.children!.length > 0){
    proxy?.$modal.msgWarning("该数据下包含子数组，不可删除！");
    return
  }
  await proxy?.$modal.confirm('是否确认删除测试树编号为"' + row.dataId + '"的数据项？');
  pd.loading = true;
  await delData(row.dataId as number).finally(() => pd.loading = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

onMounted(() => {
  pd.queryParams.type = <string>route.query.type;
  getList();
});
</script>
